<?php

namespace app\admin\controller;

use app\admin\model\OilOrder as OilOrderModel;
use app\admin\model\Wechat;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 加油订单
 *
 */
class OilOrder extends Backend
{
    /**
     * OilOrder模型对象
     * @var \app\admin\model\OilOrder
     */
    protected $model = null;

    protected $quickSearchField = ['id'];

    protected $defaultSortField = 'id,desc';

    protected $withJoinTable = ['user', 'station'];

    protected $preExcludeFields = ['createtime', 'updatetime'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\OilOrder;
    }

    protected function getModel($alias, $where){
        return $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->field('total_price/oil_price as oil')
            ->where($where);
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $export = (int)$this->request->param('export', 0);

        [$where, $alias, $limit, $order] = $this->queryBuilder();
        if($export){
            $list = $this->getModel($alias, $where)->select()->each(function($item){
                $item['oil_format'] = sprintf('%.2f', $item['oil']);
                return $item;
            });
            $this->success('', [
                'total' => $this->getModel($alias, $where)->count(),
                'list' => $list,
            ]);
        }
        // 已支付单
        $payCount = $this->getModel($alias, $where)->where('pay_time', '>', 0)->count();
        // 已支付元
        $payMoney = $this->getModel($alias, $where)->where('pay_time', '>', 0)->sum('pay_price');
        // 未支付单
        $noPayCount = $this->getModel($alias, $where)->where('pay_time', '=', 0)->count();
        // 未支付元
        $noPayMoney = $this->getModel($alias, $where)->where('pay_time', '=', 0)->sum('pay_price');
        // 已加油量
        $oil = $this->getModel($alias, $where)->where('pay_time', '>', 0)->field('total_price/oil_price as oil')->select();
        $oilTotal = 0;
        foreach($oil as $o){
            $oilTotal = bcadd((string)$o['oil'], (string)$oilTotal, 6);
        }
        $res = $this->getModel($alias, $where)->order($order)->paginate($limit)
            ->each(function ($item) {
                $item['username'] = $item['user']['real_name'] ?: ($item['user']['username'] ?: $item['user']['nickname']);
                $item['oil_format'] = sprintf('%.2f', $item['oil']);
                return $item;
            });

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'payCount' => $payCount,
            'payMoney' => $payMoney,
            'noPayCount' => $noPayCount,
            'noPayMoney' => $noPayMoney,
            'oil' => sprintf('%.2f', $oilTotal),
        ]);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->with(['user', 'station'])->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if ($data['state']) {
                    if ($row['state'] == 1) {
                        throw new ValidateException('请勿重复退款');
                    }
                    // 退款逻辑
                    $wechat = new Wechat();
                    $order = OilOrderModel::where('id', $data['order_id'])->field('pay_price,order_sn')->find();
                    $result = $wechat->getPayment()->refund->byOutTradeNumber($order['order_sn'], $data['refund_sn'], 1, $data['price'] * 100, [
                        // 可在此处传入其他参数，详细参数见微信支付文档
                        'refund_desc' => '商品退款',
                    ]);
                    if (isset($result['return_code']) && $result['return_code'] == 'FAIL') {
                        throw new ValidateException($result['return_msg']);
                    }
                    if (isset($result['result_code']) && $result['result_code'] == 'FAIL') {
                        throw new ValidateException($result['err_code_des']);
                    }
                    $data['refund_id'] = $result['refund_id'];
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        switch ($row['state']) {
            case 0:
                $row['state'] = '待支付';
                break;
            case 1:
                $row['state'] = '已支付';
                break;
            case 2:
                $row['state'] = '退款中';
                break;
            case 3:
                $row['state'] = '已退款';
                break;
        }
        $this->success('', [
            'row' => $row
        ]);
    }

}